package com.qimingyu.linkedlist.linkedreverse;

/**
 * author: cdxyz
 * 链表反转方法二
 */
public class ReverseLinkedList2 {
    public static ListNode reverseList(ListNode head) {
        ListNode newHead = null;
        ListNode p1 = head;
        while(p1 != null){
            //创建一个新的结点，把遍历得到结点的值赋给该结点，让该结点的next指向新链表的头
            //然后把这个结点赋值给新链表的头，即让新链表的头指针指向该结点
            newHead = new ListNode(p1.val,newHead);
            p1 = p1.next;
        }
        return newHead;
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(1,new ListNode(2,new ListNode(3,new ListNode(4,new ListNode(5,null)))));
        ListNode p1 = head;
        while (p1 != null){
            System.out.println("p1中存的值  " + p1.val);
            p1 = p1.next;
        }
        ListNode newHead = reverseList(head);


        System.out.println("----------------");
        ListNode p2 = newHead;
        while (p2 != null){
            System.out.println("p2中存的值  " + p2.val);
            p2 = p2.next;
        }
    }
}
